package util

import (
	"time"
	"webstack/config"

	jwt "github.com/dgrijalva/jwt-go"
)

type claims struct {
	name string
	jwt.StandardClaims
}

var jwtSecret = []byte(config.TokenSecret)

// GenerateToken 生成登陆Token
func GenerateToken(name string, expiredSecond int) (string, error) {
	if expiredSecond < config.TokenExpiredSecond {
		expiredSecond = config.TokenExpiredSecond
	}
	nowTime := time.Now()
	expireTime := nowTime.Add(time.Duration(expiredSecond) * time.Second)

	claim := claims{
		name,
		jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			Issuer:    config.AppName,
		},
	}

	tokenClaim := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
	token, err := tokenClaim.SignedString(jwtSecret)

	return token, err
}

// ParseToken 解析token
func ParseToken(token string) (*claims, error) {
	tokenClaim, err := jwt.ParseWithClaims(token, &claims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtSecret, nil
	})

	if tokenClaim != nil {
		if claims, ok := tokenClaim.Claims.(*claims); ok && tokenClaim.Valid {
			return claims, nil
		}
	}

	return nil, err
}
